package driver.android;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import driver.android.http.CommonOkHttpClient;
import driver.util.Constants;
import driver.util.IHttpCallBack;
import driver.util.NotificationUtils;
import driver.util.Util;
import okhttp3.Response;

public class FlashDriverMainActivity extends BasicActivity implements IHttpCallBack, View.OnClickListener {

    //    update tips
    private TextView mUpdateTips;
    private FlashDriverMainHandler mHandler;
    private Dialog mUpdateDialog;
    private NotificationUtils mNotificationUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f_activity_main);
        initMainAc();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNotificationUtils = new NotificationUtils(this);
        boolean isOpenNotificationSwitch = mNotificationUtils.isNotificationEnabled(this);
        Util.debugApp('d', "Main Activity onResume isOpenNotificationSwitch " + isOpenNotificationSwitch);
        if (!isOpenNotificationSwitch) {
            showToast("Please turn on system notification to receive App notification");
            mNotificationUtils.toSetting(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUpdateDialog != null && mUpdateDialog.isShowing()) {
            mUpdateDialog.dismiss();
        }
    }

    private void initMainAc() {
        mUpdateTips = this.findViewById(R.id.f_check_update_text_view);
        mHandler = new FlashDriverMainHandler(this);
        mUpdateDialog = createCustomUpdateDialog();
    }

//    get app info request
    private void getAppServerInfo() {
        int appVersion = getAppVersionInfo();
        String appName = getAppNameInfo();
        CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
        String url = Constants.ROOT + Constants.UPDATE_CHECK_URL + "?versionCode=" + String.valueOf(appVersion) + "&versionName=" + appName;
        Util.debugApp('d', "Get update apk url " + url);
        okHttpInstance.doGet(url, null, null);
    }

//    intent to  login activity
    private void jumpLoginActivity() {
        Util.debugApp('d', "intent to login activity");
        Intent intent = new Intent();
        intent.setClass(this, FlashDriverLoginActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    private void controlUpdateTipsShow(int visible) {
        mUpdateTips.setVisibility(visible);
    }

//    check update information
    private void checkUpdateDialog(Bundle bundle) {
        if (bundle != null) {
            String body = bundle.getString("appServerInfo");
            String appServerVersion = Util.getJsonKeyValue("versionCode", body);
            if (appServerVersion == null) {
                Util.debugApp('d', "app version is empty");
                jumpLoginActivity();
            } else {
                Util.debugApp('d', "app version is " + appServerVersion);
                int serverVersion = Integer.valueOf(appServerVersion);
                int appVersion = getAppVersionInfo();
                if (appVersion >= serverVersion) {
                    Util.debugApp('d', "need not update");
                    jumpLoginActivity();
                } else {
                    Util.debugApp('d', "need update");
                    controlUpdateTipsShow(View.INVISIBLE);
                    if (mUpdateDialog != null && !mUpdateDialog.isShowing()) {
                        mUpdateDialog.show();
                    } else {
                        jumpLoginActivity();
                    }
                }
            }
        }
    }


    //    custom update view
    private Dialog createCustomUpdateDialog() {
        Dialog baseDialog = new Dialog(this, R.style.BaseDialog);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.f_update_dialog_layout, null);
        baseDialog.setContentView(layout);
        Button updateAppVersionBtn = (Button) layout.findViewById(R.id.update_version_button);
        if(updateAppVersionBtn != null) {
            updateAppVersionBtn.setOnClickListener(this);
        }
        Button updateAppCancelVersionBtn = (Button) layout.findViewById(R.id.update_cancel_version_button);
        if (updateAppCancelVersionBtn != null) {
            updateAppCancelVersionBtn.setOnClickListener(this);
        }
        baseDialog.setCanceledOnTouchOutside(false);
        return baseDialog;
    }

    //    get app info
    private int getAppVersionInfo() {
        try {
            //get software version code  match AndroidManifest.xml下android:versionCode
            int versionCode = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    //    get app version info
    private String getAppNameInfo() {
        try {
            //get software version code，应AndroidManifest.xml下android:versionCode
            String versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0.0";
    }


    // check app in app store
    public boolean hadAppStore(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (packageInfo != null) {
            for (int i = 0; i < packageInfo.size(); i++) {
                String pn = packageInfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

//    show toast info
    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }

    //    start to download app
    public void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg)) {
                return;
            }
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg)) {
                intent.setPackage(marketPkg);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Util.debugApp('d', "intent to google player exception" + e.toString());
            this.jumpLoginActivity();
        }
    }

//    get app info success callback
    @Override
    public void success(Response response) {
        if (mHandler != null) {
            Message appServerInfoSuccessMessage = mHandler.obtainMessage();
            if (appServerInfoSuccessMessage != null) {
                try {
                    Bundle bundle = new Bundle();
                    String body = response.body().string();
                    bundle.putString("appServerInfo", body);
                    appServerInfoSuccessMessage.setData(bundle);
                    appServerInfoSuccessMessage.what = Constants.APP_SERVER_INFO_SUCCESS_MESSAGE;
                    Util.debugApp('d', "get App info success" + body);
                } catch (IOException e) {
                    Util.debugApp('d', "get app info success but parse erro" + e.toString());
                    e.printStackTrace();
                    appServerInfoSuccessMessage.what = Constants.APP_SERVER_INFO_FAIL_MESSAGE;
                }
                mHandler.sendMessage(appServerInfoSuccessMessage);
            }
        }
    }

//    get app info fail callback
    @Override
    public void fail(IOException exception) {
        Util.debugApp('d', "get app info fail");
        if (mHandler != null) {
            Message appServerInfoFailMessage = mHandler.obtainMessage();
            if (appServerInfoFailMessage != null) {
                appServerInfoFailMessage.what = Constants.APP_SERVER_INFO_FAIL_MESSAGE;
                mHandler.sendMessage(appServerInfoFailMessage);
            }
        }
    }

    //    get app info code invalid callback
    @Override
    public void codeInvalid(Response response) {
        Util.debugApp('d', "get App Code invalid");
        if (mHandler != null) {
            Message appServerInfoFailMessage = mHandler.obtainMessage();
            if (appServerInfoFailMessage != null) {
                appServerInfoFailMessage.what = Constants.APP_SERVER_INFO_FAIL_MESSAGE;
                mHandler.sendMessage(appServerInfoFailMessage);
            }
        }
    }

    @Override
    public void onClick(View v) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        int id = v.getId();
        switch (id) {
            case R.id.update_version_button:
                Util.debugApp('d', "start update");
                boolean appStore = this.hadAppStore(this, Constants.GOOGLE_PLAY);
                if (!appStore) {
                    Toast.makeText(this, "Please download Google Play", Toast.LENGTH_LONG).show();
                } else {
                    launchAppDetail(this, Constants.FLASH_DRIVER_PACKAGE_NAME, Constants.GOOGLE_PLAY);
                }
                break;
            case R.id.update_cancel_version_button:
                jumpLoginActivity();
                break;
        }
    }

//    main activity handler
    private static class FlashDriverMainHandler extends Handler {

        private final WeakReference<FlashDriverMainActivity> mActivity;

        private FlashDriverMainHandler(FlashDriverMainActivity ac) {
            this.mActivity = new WeakReference<FlashDriverMainActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverMainActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case Constants.APP_SERVER_INFO_SUCCESS_MESSAGE:
                        Bundle bundle = msg.getData();
                        activity.checkUpdateDialog(bundle);
                        break;
                    case Constants.APP_SERVER_INFO_FAIL_MESSAGE:
                        activity.jumpLoginActivity();
                        break;
                }
            }
        }
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
        super.afterRequestPermission(requestCode, isAllGranted);
        Util.debugApp('d', "main activity permissions status " + isAllGranted);
        getAppServerInfo();
    }
}
